package com.yjlove.myplay.utils;

import java.util.Random;

import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.GradientDrawable;
import android.graphics.drawable.StateListDrawable;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.TextView;
import android.widget.Toast;

import com.yjlove.myplay.AppContext;

/**
 * 封装UI操作的工具类
 * @author dzl
 *
 */
public class UiUtils {

	/** 在屏幕的中央显示一个Toast */
	public static void showToast(CharSequence text) {
		Toast toast = Toast.makeText(AppContext.getInstance(), text, Toast.LENGTH_SHORT);
		toast.setGravity(Gravity.CENTER, 0, 0);
		toast.show();
	}
	
	/** 把一个dp单位的值转换为px单位的值 */
	public static int dp2px(int dp) {
		float density = AppContext.getInstance().getResources().getDisplayMetrics().density;	// 获取屏幕密度
		int px = (int) (dp * density + 0.5f);
		return px;
	}

	public static int createRandomColor() {
		Random random = new Random();
		int red = 50 + random.nextInt(150);		// 50 ~ 199
		int green = 50 + random.nextInt(150);	// 50 ~ 199
		int blue = 50 + random.nextInt(150);	// 50 ~ 199
		int color = Color.rgb(red, green, blue);
		return color;
	}

	/** 创建随机颜色选择器的TextView */
	@SuppressWarnings("deprecation")
	public static TextView createRandomColorSelectorTextView() {
		final TextView textView = new TextView(AppContext.getInstance());
		textView.setTextColor(Color.WHITE);
		textView.setPadding(dp2px(6), dp2px(6), dp2px(6), dp2px(6));
		textView.setGravity(Gravity.CENTER);
		textView.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				showToast(textView.getText());
			}
		});
		textView.setBackgroundDrawable(createRandomColorSelector());
		return textView;
	}

	/** 创建随机颜色选择器 */
	private static Drawable createRandomColorSelector() {
		StateListDrawable stateListDrawable = new StateListDrawable();	// 创建一个选择器对象
		// 添加一个按下状态和按下状态要显示的Drawable
		int[] pressState = {android.R.attr.state_pressed, android.R.attr.state_enabled};
		Drawable pressDrawable = createRandomColorShape();
		stateListDrawable.addState(pressState, pressDrawable);
		
		// 添加一个正常状态和正常状态要显示的Drawable
		int[] normalState = {};
		Drawable normalDrawable = createRandomColorShape();
		stateListDrawable.addState(normalState, normalDrawable);
		return stateListDrawable;
	}

	/** 创建随机颜色的形状 */
	private static Drawable createRandomColorShape() {
		GradientDrawable gradientDrawable = new GradientDrawable();	// 创建一个图形对象
		gradientDrawable.setShape(GradientDrawable.RECTANGLE);	// 指定形状为矩形
		gradientDrawable.setCornerRadius(dp2px(6));	// 指定圆角的角度
		gradientDrawable.setColor(createRandomColor());	// 指定图形的颜色
		return gradientDrawable;
	}
}




















